package com.app.diary;

import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
import com.app.diary.data.DiaryDataSource;
import com.app.diary.data.UserDataSource;
import com.app.diary.data.impl.DiaryDataSourceImpl;
import com.app.diary.data.impl.UserDataSourceImpl;
import com.app.diary.db.DbHelper;
import android.util.Log;

public class Mapp extends Application {

    private static Mapp instance; // 单例

    private DbHelper dbHelper; // 数据库操作工具
    private DiaryDataSource diaryDataSource; // 日记数据源
    private UserDataSource userDataSource; // 账号信息
    private boolean isLoggedIn = false;
    private long userId = -1; // 用户ID，默认为无效值

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 如果你需要支持低于 Android 5.0 的设备，则保留以下行
        MultiDex.install(this);
    }

    /**
     * 获取实例
     */
    public static synchronized Mapp getInstance() {
        return instance;
    }

    /**
     * 懒加载获取数据库操作工具
     */
    public DbHelper getDbHelper() {
        if (dbHelper == null) {
            dbHelper = new DbHelper(this);
        }
        return dbHelper;
    }

    /**
     * 懒加载获取日记数据源
     */
    public DiaryDataSource getDiaryDataSource() {
        if (diaryDataSource == null && userId != -1) {
            diaryDataSource = new DiaryDataSourceImpl(getDbHelper(), userId);
        }
        return diaryDataSource;
    }

    /**
     * 懒加载获取用户数据源
     */
    public UserDataSource getUserDataSource() {
        if (userDataSource == null) {
            userDataSource = new UserDataSourceImpl(getDbHelper());
        }
        return userDataSource;
    }

    /**
     * 设置用户的登录状态
     */
    public void setUserLoggedIn(boolean loggedIn) {
        this.isLoggedIn = loggedIn;
    }

    /**
     * 获取用户的登录状态
     */
    public boolean isUserLoggedIn() {
        return isLoggedIn;
    }

    /**
     * 设置用户ID
     */
    public void setUserId(long userId) {
        this.userId = userId;
        // 重新初始化 diaryDataSource
        diaryDataSource = null;
    }

    /**
     * 获取用户ID
     */
    public long getUserId() {
        return userId;
    }
}